﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Linq;
using VOL.Core.CacheManager;
using VOL.Core.DBManager;
using VOL.Core.Extensions;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using SD = System.Drawing;
using IO = System.IO;
using VOL.Core.Extensions.AutofacManager;

namespace VOL.WebApi.Controllers.MyTable.bigscreen
{
    [Route("api/AI_Bigscreen")]
    [ApiController]
    public class AI_BigscreenController : Controller
    {
        [HttpPost, HttpGet, Route("get_seb_state"), AllowAnonymous]
        public object get_seb_state()
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            //获取所有的摄像头的基础信息
            sql = "select * from bai_device";
            sql = sql.Replace("'", "''");
            List<dynamic> t_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, "").ToList();
            List<Dictionary<string, string>> rtn_list = new List<Dictionary<string, string>>();
            //获取最近发生的5条事件用于投屏（and eventid not like '%_y%' and eventid not like '%_b%' ）
            sql = "select top 5 a.eventId e_id,a.*,b.* from bai_event a,bai_device b where a.devicetoken=b.devicetoken order by requestTime  desc";
            List<dynamic> scroll_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, "").ToList();
            List<dynamic> seb_list = new List<dynamic>();
            for (int i = 0; i <= t_list.Count() - 1; i++)
            {
                try
                {
                    Dictionary<string, string> map = new Dictionary<string, string>();
                    map.Add("x", (((string)(t_list[i].rtspAddress)) ?? "").Split(",")[0]);
                    map.Add("y", (((string)(t_list[i].rtspAddress)) ?? "").Split(",")[1]);
                    map.Add("cameid", (((string)(t_list[i].cano)) ?? ""));
                    map.Add("mc", (((string)(t_list[i].sjaddress)) ?? ""));
                    map.Add("deviceToken", (((string)(t_list[i].deviceToken)) ?? ""));
#pragma warning disable CS0162 // 检测到无法访问的代码
                    for (int ii = 0; ii < scroll_list.Count; ii++)
                    {
                        if ((string)(t_list[i].cano) == ((string)(scroll_list[ii].cano)))
                        {
                            map.Add("mess", (((string)(scroll_list[ii].skillName)) ?? ""));
                            map.Add("savapicpath", (((string)(scroll_list[ii].savapicpath)) ?? ""));
                            map.Add("requestTime", (Convert.ToString(scroll_list[ii].requestTime)));
                            map.Add("createTime", (Convert.ToString(scroll_list[ii].createTime)));
                            map.Add("e_id", (((string)(scroll_list[ii].e_id)) ?? ""));
                            break;
                        }
                        else
                        {
                            map.Add("mess", "");
                            map.Add("savapicpath", "");
                            map.Add("requestTime", "");
                            map.Add("createTime", "");
                            map.Add("e_id", "");
                            break;
                        }
                    }
#pragma warning restore CS0162 // 检测到无法访问的代码
                    rtn_list.Add(map);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

            }

            //按技能分类汇总图表
            string sqlstr = "select skillname,count(eventid) num from bai_event GROUP BY skillname";
            List<dynamic> list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            List<string> seriesData = new List<string>();//y坐标值
            List<string> categoryList = new List<string>();//x横坐标名称
            for (int i = 0; i <= list.Count() - 1; i++)
            {//添加横坐标
                categoryList.Add((string)list[i].skillname);
                seriesData.Add(Convert.ToString(list[i].num));//y坐标的值
            }
            //行为分析事件占比
            List<dynamic> seriesData_sb = new List<dynamic>();//
            List<string> categoryList_sb = new List<string>();//维度
            for (int i = 0; i <= list.Count() - 1; i++)
            {//添加横坐标
                Dictionary<String, Object> vn = new Dictionary<String, Object>();
                vn.Add("value", Convert.ToString(list[i].num));
                vn.Add("name", list[i].skillname);
                categoryList_sb.Add((string)list[i].skillname);
                seriesData_sb.Add(vn);
            }

            //通道发生事件
            sqlstr = "select (select sjaddress from bai_device where bai_device.deviceToken=bai_event.deviceToken ) tdname,count(*) tdnum from bai_event group by devicetoken order by devicetoken desc";
            List<dynamic> list_td = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            List<long> seriesData_td = new List<long>();
            List<string> categoryList_td = new List<string>();//维度
            for (int i = 0; i <= list_td.Count - 1; i++)
            {//添加横坐标
                categoryList_td.Add((string)list_td[i].tdname);
                seriesData_td.Add((long)list_td[i].tdnum);
            }

            //通道清单
            sqlstr = "select * from bai_device order by cano desc";
            List<dynamic> dongdao_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();

            //技能清单清单
            sqlstr = "select * from bai_skill where state=1 ";
            List<dynamic> jileng_list = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            //技能清单清单
            sqlstr = "select count(*) co from bai_event";
            List<dynamic> zong_count = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            //获取当天事件数量
            sqlstr = "select  count(*) co  from bai_event where CONVERT(VARCHAR(10),getdate(),120)=CONVERT(VARCHAR(10),requestTime,120) ";
            List<dynamic> todate_count = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();

            //技能列表
            sqlstr = "select distinct skillname from bai_event ";
            List<dynamic> skillnames = DBServerProvider.SqlDapper.QueryList<dynamic>(sqlstr, "").ToList();
            result.Add("seb", rtn_list);
            result.Add("scroll_list", scroll_list);
            result.Add("sk_x", categoryList);
            result.Add("sk_y", seriesData);
            result.Add("sb_name", categoryList_sb);
            result.Add("sb_value", seriesData_sb);
            result.Add("tdname", categoryList_td);
            result.Add("tdnum", seriesData_td);
            result.Add("dongdao_list", dongdao_list);
            result.Add("jileng_list", jileng_list);
            result.Add("zong_count", zong_count);
            result.Add("todate_count", todate_count);
            result.Add("skillnames", skillnames);
            return result;
        }


        [HttpPost, HttpGet, Route("get_event_mx"), AllowAnonymous]
        public object get_event_mx(string search1)
        {
            string tsql = "";
            if (search1 == "全部")
            {
                tsql = "select top 10000 requestTime rtime,(select sjaddress from bai_device where bai_device.deviceToken=bai_event.deviceToken ) sjaddress,bai_event.* from bai_event ,bai_device where bai_device.deviceToken=bai_event.deviceToken order by requestTime desc";
            }
            else
            {
                tsql = "select top 10000 requestTime rtime,(select sjaddress from bai_device where bai_device.deviceToken=bai_event.deviceToken ) sjaddress,bai_event.* from bai_event ,bai_device where bai_device.deviceToken=bai_event.deviceToken and skillname='" + search1 + "' order by requestTime desc";
                
            }
            
            Dictionary<string, object> result = new Dictionary<string, object>();
            List<dynamic> all_bai_event = DBServerProvider.SqlDapper.QueryList<dynamic>(tsql, "").ToList();
            result.Add("data", all_bai_event);
            //Console.WriteLine(tsql);
            return result;
        }

        /// <summary>
        /// 定时取AI_FPT服务器上的图片
        /// </summary>
        [HttpPost, HttpGet, Route("run_custom_ai_job"), AllowAnonymous]

        public dynamic run_custom_ai_job()
        {

           dynamic t0= base64toimg_AI_01();
            dynamic t1=base64toimg_AI_02();
            return t0;
        }

        private void run_custom_ai_job_old()
        {
            //1、下载txt文件
            string today = DateTime.Now.ToString("yyyMMdd");
            string bd_path = "c:/output/" + today;//本地文件路径
            string original_path = "c:/output/" + today+"/original";//本地原图文件路径，原图的文件名称与预测结果的图片名称一样
            string ftp_path = "/output/";//ftp服务器上的路径
            FtpClient ftpClient = new FtpClient(@"ftp://10.100.16.14" + ftp_path + today, "ctruckftp", "123456");
            ftpClient.get(today + ".txt", bd_path + "\\" + today + ".txt");
            //2、读取txt文件
            List<string> strings = new List<string>();
            StreamReader streamReader = new StreamReader(bd_path + "\\" + today + ".txt");
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                strings.Add(line);
            }
           // Console.WriteLine(string.Join(",",strings.ToArray()));
            streamReader.Close();
            streamReader.Dispose();
            //3、先查询后插入数据库,同时下载ftp上的图片
            List<Bai_event> bai_Events = DBServerProvider.DbContext.Set<Bai_event>().ToList();
            List<Bai_skill> bai_Skills = DBServerProvider.DbContext.Set<Bai_skill>().ToList();
            for (int i = 0; i < strings.Count; i++)
            {
                if (!bai_Events.Exists(e => e.eventId == strings[i]))
                {
                    string filname = strings[i];
                    string[] arr = filname.Split("_");
                    string datetiem_str = arr[1];
                    string skill = arr[2];
                    Bai_event bai_Events1 = new Bai_event();
                    bai_Events1.eventId = strings[i];
                    bai_Events1.deviceToken = arr[0];
                    bai_Events1.deviceName = arr[0];
                    bai_Events1.requestTime = DateTime.ParseExact(arr[1], "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
                    bai_Events1.createTime = DateTime.Now;
                    bai_Events1.title = bai_Skills.Where(S => S.skillid == Convert.ToInt16(skill.Substring(2))).Select(s => s.skillname).FirstOrDefault().ToString();
                    bai_Events1.skillId = bai_Skills.Where(S => S.skillid == Convert.ToInt16(skill.Substring(2))).Select(s => s.skillid).FirstOrDefault();
                    bai_Events1.skillName = bai_Skills.Where(S => S.skillid == Convert.ToInt16(skill.Substring(2))).Select(s => s.skillname).FirstOrDefault().ToString();
                    string filename_path = DateTime.Now.ToString("yyyyMMdd");
                    bai_Events1.savapicpath = bd_path + "/" + filname;
                    DBServerProvider.DbContext.Set<Bai_event>().Add(bai_Events1);
                    ftpClient.get(filname, bd_path + "\\" + filname);//预测结果
                    ftpClient.get("original\\"+filname, original_path + "\\" + filname);//下载原图

                }

            }
            DBServerProvider.DbContext.SaveChanges();
        }

        /// <summary>
        /// 取AI服务器上的图片
        /// </summary>
        [HttpPost, HttpGet, Route("get_other_pic"), AllowAnonymous]
        public object get_other_pic(string eventid)
        {
            //Console.WriteLine(eventid);
            string tsql = "select * from bai_event where eventId in(@_eventid)";
            Dictionary<string, object> result = new Dictionary<string, object>();
            List<Bai_event> all_bai_event = DBServerProvider.SqlDapper.QueryList<Bai_event>(tsql, new { _eventid = eventid }).ToList();
            string image_filename = all_bai_event[0].eventId;
            string riq = image_filename.Split("_")[1].Substring(0,8);
            FileStream fileStream = new FileStream("c:\\output\\"+ riq+"\\"+ image_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            Image file = Image.FromStream(fileStream);
            //Console.WriteLine(ConvertImageToBase64(file));
            FileStream fileStream_o = new FileStream("c:\\output\\" + riq + "\\original\\" + image_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            Image file_o = Image.FromStream(fileStream_o);
            result.Add("result_list", all_bai_event);
            result.Add("base64", ConvertImageToBase64(file));
            result.Add("base64_o", ConvertImageToBase64(file_o));
            return result;
        }

        /// <summary>
        /// 取下一条最近的PIC
        /// </summary>
        [HttpPost, HttpGet, Route("get_next_pic"), AllowAnonymous]
        public object get_next_pic(string eventid,string fx)
        {
            //Console.WriteLine(eventid);
            //string tsql = "select * from bai_event where eventId in(@_eventid)";
            Dictionary<string, object> result = new Dictionary<string, object>();
            DateTime ?e = DBServerProvider.DbContext.Set<Bai_event>().Where(w => w.eventId == eventid).Select(s => s.requestTime).FirstOrDefault();
            Bai_event be = new Bai_event();
            if (fx == "next")
            {
                be = DBServerProvider.DbContext.Set<Bai_event>().Where(w => w.requestTime < e).OrderByDescending(c => c.requestTime).FirstOrDefault();
            }
            else
            {
                be = DBServerProvider.DbContext.Set<Bai_event>().Where(w => w.requestTime > e).OrderBy(c => c.requestTime).FirstOrDefault();
            }

            Image file = null;
            try
            {
                string image_filename = be.eventId;
                string riq = image_filename.Split("_")[1].Substring(0, 8);  
                FileStream fileStream = new FileStream("c:\\output\\" + riq + "\\" + image_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                file = Image.FromStream(fileStream);
                result.Add("result_list", be);
                result.Add("base64", ConvertImageToBase64(file));
                FileStream fileStream_o = new FileStream("c:\\output\\" + riq + "\\original\\" + image_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                Image file_o = Image.FromStream(fileStream_o);
               
                result.Add("base64_o", ConvertImageToBase64(file_o));
            }
            catch(Exception ee)
            {
                Console.WriteLine(ee.Message);
                //result.Add("base64", "");

            }
            
            //Console.WriteLine(ConvertImageToBase64(file));

           
            return result;
        }

        private string ConvertImageToBase64(Image file)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                file.Save(memoryStream, file.RawFormat);
                byte[] imageBytes = memoryStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }

        
        public static dynamic base64toimg_AI_01()//
        {
            ICacheService cacheService = AutofacContainerModule.GetService<ICacheService>();
            string isdu = cacheService.Get<string>("AI01_RIGHT");
            List<string> single_result = new List<string>();
            if (isdu == "0")//是0才读取
            {
                string tt = cacheService.Get<string>("AI01_OUTPUT");

                List<string> ar = tt.Split(";").ToList();
                byte[] arr = Convert.FromBase64String(ar[2]);//图片
                string ip = ar[0];
                string results = ar[1]; //"1186,197,27,32,1.000000,0.636116,1069,191,26,29,1.000000,0.620277,1165,217,39,44,1.000000,0.500";//
                string[] array_results = results.Split(",");
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bitmap = (Bitmap)Image.FromStream(ms);
                Bitmap old_bitmap = (Bitmap)Image.FromStream(ms);
                // string savepath = "d:\\AI_OUTPUT\\";
                string today = DateTime.Now.ToString("yyyMMdd");
                string bd_path = "c:/output/" + today + "/";//本地文件路径
                string original_path = "c:/output/" + today + "/original/";//本地原图文件路径，原图的文件名称与预测结果的图片名称一样
                //path_create(savepath);
                path_create(bd_path);
                path_create(original_path);

                if (!string.IsNullOrEmpty(results))
                {
                    // int res_cout = results.Count() / 6;

                    string t = "";
                    for (int i = 0; i < array_results.Length; i++)
                    {
                        int co = i + 1;

                        if ((co % 6) != 0)
                        {
                            t = t + array_results[i] + ",";
                        }
                        else
                        {
                            t = t + array_results[i];
                            single_result.Add(t);
                            t = "";
                        }

                    }
                    string zxd = "";
                    foreach (var item in single_result)
                    {
                        string[] ponit = item.Split(",");
                        List<int> pints = new List<int>();
                        for (int i = 0; i <= 3; i++)
                        {
                            pints.Add(Convert.ToInt16(ponit[i]));
                        }

                        double Confidence = Convert.ToDouble(ponit[5]);
                        if (Confidence <= 0.6) continue;//小于0.6直接舍去

                        int op = (int)Convert.ToDouble(ponit[4]);//ai类型
                        //Console.WriteLine(op);
                        string label = "";
                        if (op == 1)
                        {
                            label = "nohat";
                        }
                        else
                        {
                            label = "hat";
                        }
                        zxd = zxd + label + "(" + Confidence.ToString() + ")";
                        Rectangle rect = new Rectangle(pints[0], pints[1], pints[2], pints[3]);

                        DrawRectangleInPicture(bitmap, label, Confidence, rect, Color.Yellow, 1, DashStyle.Solid);
                    }

                    if (!string.IsNullOrEmpty(zxd))
                    {//置信度不等于空才存盘
                        string skill = "safehat";
                        string filename = "cam-" + ip + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + skill + "_" + zxd + ".Jpeg";
                        string rq = DateTime.Now.ToString("yyyyMMdd");
                       /* StreamWriter sw = IO.File.AppendText(bd_path + rq + ".txt");

                        sw.WriteLine(filename);
                        sw.Flush();
                        sw.Close();*/
                        bitmap.Save(bd_path + filename, SD.Imaging.ImageFormat.Jpeg);
                        old_bitmap.Save(original_path + filename, SD.Imaging.ImageFormat.Jpeg);//原图

                        List<Bai_event> bai_Events = DBServerProvider.DbContext.Set<Bai_event>().ToList();
                        List<Bai_skill> bai_Skills = DBServerProvider.DbContext.Set<Bai_skill>().ToList();
                        Bai_event bai_Events1 = new Bai_event();
                       
                        bai_Events1.eventId = filename;
                        bai_Events1.deviceToken = filename.Split("_")[0];
                        bai_Events1.deviceName = filename.Split("_")[0];
                        bai_Events1.requestTime = DateTime.ParseExact(filename.Split("_")[1], "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
                        bai_Events1.createTime = DateTime.Now;
                        bai_Events1.title = bai_Skills.Where(S => S.customid =="01").Select(s => s.skillname).FirstOrDefault().ToString();
                        bai_Events1.skillId = bai_Skills.Where(S => S.customid == "01").Select(s => s.skillid).FirstOrDefault();
                        bai_Events1.skillName = bai_Skills.Where(S => S.customid == "01").Select(s => s.skillname).FirstOrDefault().ToString();
                        string filename_path = DateTime.Now.ToString("yyyyMMdd");
                        bai_Events1.savapicpath = bd_path + "/" + filename;
                        DBServerProvider.DbContext.Set<Bai_event>().Add(bai_Events1);

                    }

                }
                cacheService.AddObject("AI01_RIGHT", 1);
                DBServerProvider.DbContext.SaveChanges();
            }

            return single_result;
        }

        /// <summary>
        /// 增加个技能，需要修改5处地方
        /// </summary>
        /// <returns></returns>
        public static dynamic base64toimg_AI_02()//
        {
            ICacheService cacheService = AutofacContainerModule.GetService<ICacheService>();
            string isdu = cacheService.Get<string>("AI02_RIGHT");//修改1
            List<string> single_result = new List<string>();
            if (isdu == "0")//是0才读取
            {
                string tt = cacheService.Get<string>("AI02_OUTPUT");//修改2

                List<string> ar = tt.Split(";").ToList();
                byte[] arr = Convert.FromBase64String(ar[2]);//图片
                string ip = ar[0];
                string results = ar[1]; //"1186,197,27,32,1.000000,0.636116,1069,191,26,29,1.000000,0.620277,1165,217,39,44,1.000000,0.500";//
                string[] array_results = results.Split(",");
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bitmap = (Bitmap)Image.FromStream(ms);
                Bitmap old_bitmap = (Bitmap)Image.FromStream(ms);
                // string savepath = "d:\\AI_OUTPUT\\";
                string today = DateTime.Now.ToString("yyyMMdd");
                string bd_path = "c:/output/" + today + "/";//本地文件路径
                string original_path = "c:/output/" + today + "/original/";//本地原图文件路径，原图的文件名称与预测结果的图片名称一样
                //path_create(savepath);
                path_create(bd_path);
                path_create(original_path);

                if (!string.IsNullOrEmpty(results))
                {
                    // int res_cout = results.Count() / 6;

                    string t = "";
                    for (int i = 0; i < array_results.Length; i++)
                    {
                        int co = i + 1;

                        if ((co % 6) != 0)
                        {
                            t = t + array_results[i] + ",";
                        }
                        else
                        {
                            t = t + array_results[i];
                            single_result.Add(t);
                            t = "";
                        }

                    }
                    string zxd = "";
                    foreach (var item in single_result)
                    {
                        string[] ponit = item.Split(",");
                        List<int> pints = new List<int>();
                        for (int i = 0; i <= 3; i++)
                        {
                            pints.Add(Convert.ToInt16(ponit[i]));
                        }

                        double Confidence = Convert.ToDouble(ponit[5]);
                        if (Confidence <= 0.5) continue;//小于0.6直接舍去

                        int op = (int)Convert.ToDouble(ponit[4]);//ai类型
                        //Console.WriteLine(op);
                        string label = "";
                        if (op == 1)//修改3
                        {
                            label = "nosmoke";
                        }
                        else
                        {
                            label = "smoke";
                        }
                        zxd = zxd + label + "(" + Confidence.ToString() + ")";
                        Rectangle rect = new Rectangle(pints[0], pints[1], pints[2], pints[3]);

                        DrawRectangleInPicture(bitmap, label, Confidence, rect, Color.Yellow, 1, DashStyle.Solid);
                    }

                    if (!string.IsNullOrEmpty(zxd))
                    {//置信度不等于空才存盘
                        string skill = "smoke";
                        string filename = "cam-" + ip + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + skill + "_" + zxd + ".Jpeg";
                        string rq = DateTime.Now.ToString("yyyyMMdd");
                        /*StreamWriter sw = IO.File.AppendText(bd_path + rq + ".txt");

                        sw.WriteLine(filename);
                        sw.Flush();
                        sw.Close();*/
                        bitmap.Save(bd_path + filename, SD.Imaging.ImageFormat.Jpeg);
                        old_bitmap.Save(original_path + filename, SD.Imaging.ImageFormat.Jpeg);//原图

                        List<Bai_event> bai_Events = DBServerProvider.DbContext.Set<Bai_event>().ToList();
                        List<Bai_skill> bai_Skills = DBServerProvider.DbContext.Set<Bai_skill>().ToList();
                        Bai_event bai_Events1 = new Bai_event();

                        bai_Events1.eventId = filename;
                        bai_Events1.deviceToken = filename.Split("_")[0];
                        bai_Events1.deviceName = filename.Split("_")[0];
                        bai_Events1.requestTime = DateTime.ParseExact(filename.Split("_")[1], "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
                        bai_Events1.createTime = DateTime.Now;
                        bai_Events1.title = bai_Skills.Where(S => S.customid == "02").Select(s => s.skillname).FirstOrDefault().ToString();//修改5
                        bai_Events1.skillId = bai_Skills.Where(S => S.customid == "02").Select(s => s.skillid).FirstOrDefault();
                        bai_Events1.skillName = bai_Skills.Where(S => S.customid == "02").Select(s => s.skillname).FirstOrDefault().ToString();
                        string filename_path = DateTime.Now.ToString("yyyyMMdd");
                        bai_Events1.savapicpath = bd_path + "/" + filename;
                        DBServerProvider.DbContext.Set<Bai_event>().Add(bai_Events1);

                    }

                }
                cacheService.AddObject("AI02_RIGHT", 1);//修改5
                DBServerProvider.DbContext.SaveChanges();
            }

            return single_result;
        }


        static void path_create(string path_str)
        {
            if (!Directory.Exists(path_str))
            {
                Directory.CreateDirectory(path_str);
            }
        }


        public static Bitmap? DrawRectangleInPicture(Bitmap bmp, string label, double prob, Rectangle rect, Color RectColor, int LineWidth, DashStyle ds)
        {
            try
            {
                if (bmp == null) return null;

                Graphics g = Graphics.FromImage(bmp);

                Brush brush = new SolidBrush(RectColor);
                Pen pen = new Pen(brush, LineWidth);
                pen.DashStyle = ds;
                SolidBrush drawBush = new SolidBrush(Color.Red);
                Font drawFont = new Font("Arial", 5, FontStyle.Regular, GraphicsUnit.Millimeter);
                //Size sz = TextRenderer.MeasureText(label + prob.ToString("F2"), drawFont);
                //g.DrawString(label + " " + prob.ToString("F2"), drawFont, drawBush, rect.Left, rect.Bottom+ sz.Height);
                g.DrawString(label + " " + prob.ToString("F2"), drawFont, drawBush, rect.Left, rect.Bottom);

                g.DrawRectangle(pen, rect);
                SD.Color Mycolor = SD.Color.FromArgb(50, Color.Yellow);//透明度1-255
                SD.SolidBrush SB1 = new SD.SolidBrush(Mycolor);
                g.FillRectangle(SB1, rect);
                g.Dispose();

                return bmp;
            }
            catch (Exception) { return null; }
        }

    }
}
